package com.check.operation;

import android.app.Activity;
import android.app.Application;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.check.operation.model.Ssroom;
import com.check.operation.model.Sysdiclist;
import com.check.operation.model.UserRe;
import com.szj.util.SysUtil;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalDb;

import org.androidannotations.annotations.EApplication;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

@EApplication
public class CheckApplication extends Application {
    static CheckApplication app;

    /** 本应用的根目录 */
    public static final String ROOT_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sshcapp/";
    private static final String LOG_DIR = ROOT_DIR + "/log/";
    private static final String LOG_NAME = getCurrentDateString() + ".txt";
    private ArrayList<Activity> list = new ArrayList<Activity>();
    private FinalDb finalDb;
    private FinalBitmap finalBitmap;
    private Bitmap loadingBitmap;
    private Date date;
    private UserRe userRe;
    private List<Ssroom> ssrooms;
    private Map<String, Map<String, String>> dics = new HashMap<String, Map<String, String>>();
    private List<Sysdiclist> ssbwall;
    private List<Sysdiclist> sfdgdic;
    private boolean iscn = false;// 扫描头充能

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public Bitmap getLoadingBitmap() {
        return loadingBitmap;
    }

    public void setLoadingBitmap(Bitmap loadingBitmap) {
        this.loadingBitmap = loadingBitmap;
    }

    public FinalBitmap getFinalBitmap() {
        return finalBitmap;
    }

    public void setFinalBitmap(FinalBitmap finalBitmap) {
        this.finalBitmap = finalBitmap;
    }

    public FinalDb getFinalDb() {
        return finalDb;
    }

    public void setFinalDb(FinalDb finalDb) {
        this.finalDb = finalDb;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(handler);
        app = this;
        finalDb = FinalDb.create(this, "sshc.db", true);
        finalBitmap = FinalBitmap.create(this);
        loadingBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.loading);
        SysUtil.setApplicationName("api/touch");
        SysUtil.setPort("9998");// 正式 9999
        SysUtil.setServerIp("199.199.4.174");
    }

    Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable ex) {
            try {
                writeErrorLog(ex);
                ex.printStackTrace();
                Toast.makeText(getApplicationContext(), "系统异常退出", Toast.LENGTH_LONG).show();
                exit();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public static CheckApplication getInstance() {
        if(app != null) {
            return app;
        }
        return null;
    }

    /**
     * 打印错误日志
     *
     * @param ex
     */
    protected void writeErrorLog(Throwable ex) {
        String info = null;
        ByteArrayOutputStream baos = null;
        PrintStream printStream = null;
        try {
            baos = new ByteArrayOutputStream();
            printStream = new PrintStream(baos);
            ex.printStackTrace(printStream);
            byte[] data = baos.toByteArray();
            info = new String(data);
            data = null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (printStream != null) {
                    printStream.close();
                }
                if (baos != null) {
                    baos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Log.d("example", "崩溃信息\n" + info);
        File dir = new File(LOG_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, LOG_NAME);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file, true);
            fileOutputStream.write(info.getBytes());
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取当前日期
     *
     * @return
     */
    private static String getCurrentDateString() {
        String result = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        Date nowDate = new Date();
        result = sdf.format(nowDate);
        return result;
    }

    /**
     * Activity关闭时，删除Activity列表中的Activity对象
     */
    public void removeActivity(Activity a) {
        list.remove(a);
    }

    /**
     * 向Activity列表中添加Activity对象
     */
    public void addActivity(Activity a) {
        list.add(a);
    }

    /**
     * 关闭Activity列表中的所有Activity
     */
    public void exit() {
        for (Activity activity : list) {
            if (null != activity) {
                activity.finish();
            }
        }
        // 杀死该应用进程
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * 获取最后一个activity,就是当前显示的activity
     *
     * @return
     */
    public Activity currentActivity() {
        return list.get(list.size() - 1);
    }

    public Map<String, Object> getParams() {

        return new HashMap<String, Object>();
    }

    public UserRe getUserRe() {
        return userRe;
    }

    public void setUserRe(UserRe userRe) {
        this.userRe = userRe;
    }

    public List<Ssroom> getSsrooms() {
        return ssrooms;
    }

    public void setSsrooms(List<Ssroom> ssrooms) {
        Collections.sort(ssrooms);
        this.ssrooms = ssrooms;
    }

    public Map<String, Map<String, String>> getDics() {
        return dics;
    }

    public void setDics(Map<String, Map<String, String>> dics) {
        this.dics = dics;
    }

    public List<Sysdiclist> getSsbwall() {
        return ssbwall;
    }

    public void setSsbwall(List<Sysdiclist> ssbwall) {
        this.ssbwall = ssbwall;
    }

    public List<Sysdiclist> getSfdgdic() {
        return sfdgdic;
    }

    public void setSfdgdic(List<Sysdiclist> sfdgdic) {
        this.sfdgdic = sfdgdic;
    }

    public boolean isIscn() {
        return iscn;
    }

    public void setIscn(boolean iscn) {
        this.iscn = iscn;
    }
}
